package com.gavin.sample.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AESUtil {
	public static final String AES = "AES";
	
	public static String genKeyAES() throws Exception {
		KeyGenerator keyGen = KeyGenerator.getInstance(AES);
		keyGen.init(128);
		SecretKey key = keyGen.generateKey();
		String base64Str = Base64.encodeBase64String(key.getEncoded());
		return base64Str;
	}
	
	public static SecretKey loadKeyAES(String base64Key) {
		byte[] bytes = Base64.decodeBase64(base64Key);
		SecretKey key = new SecretKeySpec(bytes, AES);
		return key;
	}
	
	public static byte[] encryptAES(byte[] source, SecretKey key) throws Exception {
		Cipher cipher = Cipher.getInstance(AES);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] bytes = cipher.doFinal(source);
		return bytes;
	}
	
	public static byte[] decryptAES(byte[] source, SecretKey key) throws Exception {
		Cipher cipher = Cipher.getInstance(AES);
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] bytes = cipher.doFinal(source);
		return bytes;
	}
	
	public static void main(String[] args) throws Exception {
		String KeyAES = genKeyAES();
		System.out.println("AES key:" + KeyAES);
		SecretKey secretKey = loadKeyAES(KeyAES);
		
		String str = "hi,i'm gavin";
		System.out.println("the string is " + str);
		byte[] encryptBytes = encryptAES(str.getBytes("UTF-8"), secretKey);
		String encryptStr = Base64.encodeBase64String(encryptBytes);
		System.out.println("the string after encrypt by DES is " + encryptStr);
		byte[] decryptBytes = decryptAES(Base64.decodeBase64(encryptStr), secretKey);
		String decryptStr = new String(decryptBytes, "UTF-8");
		System.out.println("the string after decrypt by DES is " + decryptStr);
	}
}
